<template>
  <view class="container" :class="{ 'scroll-locked': isPopupOpen }">
		
		<!-- 搜索框 -->
		<view class="search-container">
			<view class="search-box">
				<uni-icons type="search" size="14" color="#999"></uni-icons>
				<input 
					type="text" 
					placeholder="搜索订单名称" 
					v-model="searchKeyword" 
					@confirm="handleSearch"
					@input="handleInput"
				/>
				<view v-if="searchKeyword" class="clear-btn" @click="clearSearch">
					<uni-icons type="closeempty" size="14" color="#999"></uni-icons>
				</view>
			</view>
		</view>
		
    <!-- 头部筛选栏 -->
    <view class="filter-bar">
      <view class="filter-item" @click="openStatusPopup">
        <text>{{ selectedStatusText || '全部状态' }}</text>
        <uni-icons type="arrowdown" size="14" />
      </view>
<!--      <view class="filter-item" @click="openTimePopup">
        <text>{{ selectedTimeText || '全部时间' }}</text>
        <uni-icons type="arrowdown" size="14" />
      </view> -->
      <view class="filter-item" @click="openTypePopup">
        <text>{{ selectedTypeText || '全部类型' }}</text>
        <uni-icons type="arrowdown" size="14" />
      </view>
<!--      <view class="filter-item" @click="openAmountPopup">
        <text>{{ selectedAmountText || '全部金额' }}</text>
        <uni-icons type="arrowdown" size="14" />
      </view> -->
    </view>

    <!-- 状态筛选弹窗 -->
    <uni-popup ref="statusPopup" type="bottom" @open="onPopupOpen" @close="onPopupClose">
      <view class="popup-content">
        <view class="popup-header">
          <view class="popup-title">选择订单状态</view>
          <view class="popup-close" @click="statusPopup.close()">
            <uni-icons type="close" size="18" />
          </view>
        </view>
				<view class="popup-options" @touchmove.stop>
			
          <view class="option-item" :class="{ 'active': selectedStatus === null }" @click="selectStatus(null)">
            全部状态
          </view>
					
					<view
						v-for="(item, index) in orderStateOp" :key="index"
						class="option-item" 
						:class="{ 'active': selectedStatus === item.dictValue }" 
						@click="selectStatus(item.dictValue)"
					>
					  {{ item.dictLabel }}
					</view>
				</view>
      </view>
		</uni-popup>
    

    <!-- 时间筛选弹窗 -->
    <uni-popup ref="timePopup" type="bottom" @open="onPopupOpen" @close="onPopupClose">
      <view class="popup-content">
        <view class="popup-header">
          <view class="popup-title">选择时间范围</view>
          <view class="popup-close" @click="timePopup.close()">
            <uni-icons type="close" size="18" />
          </view>
        </view>
        <view class="popup-options" @touchmove.stop>
          <view class="option-item" :class="{ 'active': selectedTime === null }" @click="selectTime(null)">
            全部时间
          </view>
          <view class="option-item" :class="{ 'active': selectedTime === 'today' }" @click="selectTime('today')">
            今天
          </view>
          <view class="option-item" :class="{ 'active': selectedTime === 'yesterday' }" @click="selectTime('yesterday')">
            昨天
          </view>
          <view class="option-item" :class="{ 'active': selectedTime === 'week' }" @click="selectTime('week')">
            本周
          </view>
          <view class="option-item" :class="{ 'active': selectedTime === 'month' }" @click="selectTime('month')">
            本月
          </view>
          <view class="option-item" :class="{ 'active': selectedTime === 'year' }" @click="selectTime('year')">
            今年
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 类型筛选弹窗 -->
    <uni-popup ref="typePopup" type="bottom" @open="onPopupOpen" @close="onPopupClose">
      <view class="popup-content">
        <view class="popup-header">
          <view class="popup-title">选择订单类型</view>
          <view class="popup-close" @click="typePopup.close()">
            <uni-icons type="close" size="18" />
          </view>
        </view>
        <view class="popup-options" @touchmove.stop>
          <view class="option-item" :class="{ 'active': selectedType === null }" @click="selectType(null)">
            全部类型
          </view>
					
					<view
						v-for="(item, index) in orderTypeOp" :key="index"
						class="option-item" 
						:class="{ 'active': selectedType === item.dictValue }" 
						@click="selectType(item.dictValue)"
					>
					  {{ item.dictLabel }}
					</view>

        </view>
      </view>
    </uni-popup>

    <!-- 金额筛选弹窗 -->
    <uni-popup ref="amountPopup" type="bottom" @open="onPopupOpen" @close="onPopupClose">
      <view class="popup-content">
        <view class="popup-header">
          <view class="popup-title">选择金额范围</view>
          <view class="popup-close" @click="amountPopup.close()">
            <uni-icons type="close" size="18" />
          </view>
        </view>
        <view class="popup-options" @touchmove.stop>
          <view class="option-item" :class="{ 'active': selectedAmount === null }" @click="selectAmount(null)">
            全部金额
          </view>
          <view class="option-item" :class="{ 'active': selectedAmount === '0-100000' }" @click="selectAmount('0-100000')">
            0-100000元
          </view>
          <view class="option-item" :class="{ 'active': selectedAmount === '100000-500000' }" @click="selectAmount('100000-500000')">
            100000-500000元
          </view>
          <view class="option-item" :class="{ 'active': selectedAmount === '500000-1000000' }" @click="selectAmount('500000-1000000')">
            500000-1000000元
          </view>
          <view class="option-item" :class="{ 'active': selectedAmount === '1000+' }" @click="selectAmount('1000000+')">
            1000000元以上
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 订单列表 -->
    <view class="order-list">
			<view v-if="searchKeyword && !orderList.length" class="no-result">
				<text>没有找到与"{{ searchKeyword }}"相关的订单</text>
			</view>
      <view class="order-item" v-for="(item, index) in orderList" :key="index" @click="goDetail(item)">
        <view class="order-header">
          <text class="order-time">{{ item.createTime }}</text>
          <text class="order-status" :class="getStatusClass(item.orderStatus)">{{ getStatusText(item.orderStatus) }}</text>
        </view>
        <view class="order-content">
          <image class="order-image" :src="item.imageUrl" mode="aspectFill"></image>
          <view class="order-info">
            <text class="order-name">{{ item.orderName }}</text>
            <text class="order-desc">
							<text v-if="item.orderAddress">{{ item.orderAddress }}</text>
						</text>
            <view class="order-bottom">
              <text class="order-amount">
								<text v-if="item.orderPrice">{{ '¥' + item.orderPrice }}</text>
							</text>
              <text class="order-count">数量:{{ item.number }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading" v-if="loading">
      <uni-icons type="loading" size="18" color="#999"></uni-icons>
      <text>加载中...</text>
    </view>
    
    <!-- 没有更多数据 -->
    <view class="no-more-data" v-if="!loading && noMore && !searchKeyword">
      <text>没有更多数据了</text>
    </view>
  </view>
</template>

<script>
import { isEmpty } from "../../utils/utils";
import request from "/utils/request.js"
import { convertArrayToMap } from "/utils/utils.js"
export default {
  data() {
    return {
			// 搜索关键词
      searchKeyword: '',
			
      // 筛选条件
      selectedStatus: null,
      selectedStatusText: '',
      selectedTime: null,
      selectedTimeText: '',
      selectedType: null,
      selectedTypeText: '',
      selectedAmount: null,
      selectedAmountText: '',
      
      // 订单数据
      orderList: [],
			nowOrderList: [],
      page: 1,
      pageSize: 10,
      loading: false,
      noMore: false,
      
      // 模拟订单类型映射
      orderTypes: {
        1: 'normal',
        2: 'group',
        3: 'flash',
        4: 'presale'
      },
			orderTypeOp: [],
			typeMap: {
				null: '全部类型',
			},
			
			orderStateOp: [],
			stateMap: {
				null: '全部状态',
			},
      
      // 弹窗状态
      isPopupOpen: false,
      
      // 设备信息
      deviceInfo: null,
      isIOS: false,
			searchTimer: null,
    }
  },
  onLoad() {
    // 获取弹窗引用
    this.statusPopup = this.$refs.statusPopup;
    this.timePopup = this.$refs.timePopup;
    this.typePopup = this.$refs.typePopup;
    this.amountPopup = this.$refs.amountPopup;
    
    // 获取设备信息
    this.deviceInfo = uni.getSystemInfoSync();
    this.isIOS = this.deviceInfo.platform === 'ios';
    
		this.getOrderTypeOp();
		this.getOrderStateOp();
    this.getOrderList();
  },
  methods: {
    // 获取订单列表
    async getOrderList() {
      // 如果正在加载或者没有更多数据，则不执行
      if (this.loading || this.noMore) return;
      
      this.loading = true;

			await this.getList();
			
			// 应用筛选条件
			// let filterData = this.filterOrders(this.nowOrderList);
			let filterData = this.nowOrderList;
			
			// 判断是否还有更多数据
			if (filterData.length < this.pageSize) {
				this.noMore = true;
			}
			
			// 合并数据 
			if (this.page === 1) {
				this.orderList = filterData;
			} else {
				this.orderList = [...this.orderList, ...filterData];
			}
			
			// 更新页码和加载状态
			this.page++;
			this.loading = false;
    },
		
		// 获取订单类型
		getOrderTypeOp() {
		
			request.get('/system/dict/data/type/order_type').then( r => {
				if (r.code == 200) {
					// dictLabel  dictValue
					this.orderTypeOp = r.data
					this.typeMap = {
						...this.typeMap,
						...convertArrayToMap(r.data)
					} 
				} else {
					uni.showToast({
						title: r.msg,
						icon: 'error'
					})
				}
			})
		},
		// 获取订单状态
		getOrderStateOp() {
			request.get('/system/dict/data/type/order_status').then( r => {
				if (r.code == 200) {
					// dictLabel  dictValue
					this.orderStateOp = r.data
					this.stateMap = {
						...this.stateMap,
						...convertArrayToMap(r.data)
					} 
				} else {
					uni.showToast({
						title: r.msg,
						icon: 'error'
					})
				}
			})
		},
		
		handleInput() {
			// 防抖处理
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
			}
			
			this.searchTimer = setTimeout(() => {
				this.resetAndReload();
			}, 300);
		},
		
    // 筛选订单
    filterOrders(orders) {
      let filtered = [...orders];
      
      // 状态筛选
      if (this.selectedStatus !== null) {
        filtered = filtered.filter(order => order.orderStatus === this.selectedStatus);
      }
      
      // 时间筛选
      if (this.selectedTime) {
        const now = new Date();
        const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        
        filtered = filtered.filter(order => {
          const orderDate = new Date(order.createTime);
          
          switch (this.selectedTime) {
            case 'today':
              return orderDate >= todayStart;
            case 'yesterday':
              const yesterdayStart = new Date(todayStart);
              yesterdayStart.setDate(yesterdayStart.getDate() - 1);
              return orderDate >= yesterdayStart && orderDate < todayStart;
            case 'week':
              const weekStart = new Date(todayStart);
              weekStart.setDate(weekStart.getDate() - 6);
              return orderDate >= weekStart;
            case 'month':
              const monthStart = new Date(todayStart);
              monthStart.setMonth(monthStart.getMonth() - 1);
              return orderDate >= monthStart;
            case 'year':
              const yearStart = new Date(todayStart);
              yearStart.setFullYear(yearStart.getFullYear() - 1);
              return orderDate >= yearStart;
            default:
              return true;
          }
        });
      }
      
      // 类型筛选
      if (this.selectedType) {
        filtered = filtered.filter(order => {
          // 将状态映射为类型
          const orderType = this.orderTypes[order.orderStatus % 4 + 1];
          return orderType === this.selectedType;
        });
      }
      
      // 金额筛选
      if (this.selectedAmount) {
        filtered = filtered.filter(order => {
          const amount = order.orderPrice;
          
          if (this.selectedAmount === '0-100000') {
            return amount >= 0 && amount < 100000;
          } else if (this.selectedAmount === '100000-500000') {
            return amount >= 100000 && amount < 500000;
          } else if (this.selectedAmount === '500000-1000000') {
            return amount >= 500000 && amount < 1000000;
          } else if (this.selectedAmount === '1000000+') {
            return amount >= 1000000;
          }
          
          return true;
        });
      }
      
      return filtered;
    },
    
		async getList() {
			let params = {
				pageNum: this.page,
				pageSize: this.pageSize,
			}
			
			if (!isEmpty(this.selectedStatus)) {
				params.orderStatus = this.selectedStatus
			}
			if (!isEmpty(this.selectedType)) {
				params.orderType = this.selectedType
			}
			if (!isEmpty(this.searchKeyword)) {
				params.orderName = this.searchKeyword
			}
			
			await request.get('/system/initiate/list', {
				...params
			}).then(res => {
				if (res.code == 200) {
					this.nowOrderList = res.rows.map((v, i) => {
						return {
							...v,
							imageUrl: 'https://picsum.photos/200/200?random=' + i,
						}
					})
				} else {
					uni.showToast({
						title: r.msg,
						icon: 'error'
					})
				}
			})
		},
		
    // 生成模拟数据
    generateMockData(page) {
      const list = [];
      const start = (page - 1) * this.pageSize + 1;
      const end = start + this.pageSize;
      
      for (let i = start; i < end; i++) {
        const status = Math.floor(Math.random() * 4) + 1;
        const daysAgo = Math.floor(Math.random() * 30); // 随机0-30天前
        const amount = Math.random() * 150000 + 10; // 10-1510元
        
        list.push({
          id: i,
          name: `订单${i}`,
          desc: `这是订单${i}的简要描述信息`,
          imageUrl: 'https://picsum.photos/200/200?random=' + i,
          status,
          createTime: this.formatDate(new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000)),
          amount,
          count: Math.floor(Math.random() * 10) + 1
        });
      }
      
      return list;
    },
    
    // 日期格式化
    formatDate(date) {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    // 获取状态文本
    getStatusText(status) {
      return this.stateMap[status] || '未知状态';
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const map = {
        0: 'status-pending',
        1: 'status-paid',
        2: 'status-completed',
        3: 'status-canceled'
      };
      return map[status] || '';
    },
    
		goDetail(item) {
			uni.navigateTo({
				url: `/pages/workorder/initiateOrder?orderId=${item.id}&orderStatus=${item.orderStatus}`
			})
		},
		
    // 重置并重新加载数据
    resetAndReload() {
      this.page = 1;
      this.orderList = [];
      this.noMore = false;
      this.getOrderList();
    },
    
    // 状态筛选相关方法
    openStatusPopup() {
      this.statusPopup.open();
    },
    
    selectStatus(status) {
      this.selectedStatus = status;
      this.selectedStatusText = status === null ? '全部状态' : this.getStatusText(status);
      this.statusPopup.close();
      this.resetAndReload();
    },
    
    // 时间筛选相关方法
    openTimePopup() {
      this.timePopup.open();
    },
    
    selectTime(time) {
      const timeMap = {
        null: '全部时间',
        'today': '今天',
        'yesterday': '昨天',
        'week': '本周',
        'month': '本月',
        'year': '今年'
      };
      
      this.selectedTime = time;
      this.selectedTimeText = timeMap[time] || '全部时间';
      this.timePopup.close();
      this.resetAndReload();
    },
    
    // 类型筛选相关方法
    openTypePopup() {
      this.typePopup.open();
    },
    
    selectType(type) {
      this.selectedType = type;
      this.selectedTypeText = this.typeMap[type] || '全部类型';
      this.typePopup.close();
      this.resetAndReload();
    },
		
    
    // 金额筛选相关方法
    openAmountPopup() {
      this.amountPopup.open();
    },
    
    selectAmount(amount) {
      const amountMap = {
        null: '全部金额',
        '0-100000': '0-100000元',
        '100000-500000': '100000-500000元',
        '500000-1000000': '500000-1000000元',
        '10000000': '10000000元以上'
      };
      
      this.selectedAmount = amount;
      this.selectedAmountText = amountMap[amount] || '全部金额';
      this.amountPopup.close();
      this.resetAndReload();
    },
    
    // 弹窗状态管理
    onPopupOpen() {
      this.isPopupOpen = true;
      
      // 记录当前滚动位置（iOS兼容性处理）
      if (this.isIOS) {
        this.scrollTop = uni.getSystemInfoSync().windowHeight;
        // 延迟执行以确保iOS设备上的兼容性
        setTimeout(() => {
          document.body.style.position = 'fixed';
          document.body.style.top = `-${this.scrollTop}px`;
          document.body.style.width = '100%';
        }, 0);
      }
    },
    
    onPopupClose() {
      this.isPopupOpen = false;
      
      // 恢复滚动位置（iOS兼容性处理）
      if (this.isIOS) {
        setTimeout(() => {
          document.body.style.position = '';
          document.body.style.top = '';
          document.body.style.width = '';
          uni.pageScrollTo({
            scrollTop: this.scrollTop,
            duration: 0
          });
        }, 0);
      }
    }
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    this.resetAndReload();
    uni.stopPullDownRefresh();
  },
  
  // 上拉加载
  onReachBottom() {
    // 只有在没有搜索关键词或者搜索结果不足一页时才加载更多
		if (!this.searchKeyword || (this.searchKeyword && this.orderList.length >= this.pageSize)) {
			this.getOrderList();
		}
  }
}
</script>

<style lang="scss">
.container {
  padding-bottom: 20px;
  
  // 弹窗打开时锁定滚动
  &.scroll-locked {
    // iOS和安卓不同的滚动锁定方案
    @media (any-hover: none) {
      // 移动设备
      overflow: hidden;
      
      // iOS特殊处理
      @supports (-webkit-overflow-scrolling: touch) {
        position: fixed;
        width: 100%;
        height: 100%;
      }
    }
  }
}

/* 搜索框样式 */
.search-container {
  padding: 10px;
  background-color: #f5f5f5;
  
  .search-box {
    display: flex;
    align-items: center;
    height: 36px;
    background-color: #fff;
    border-radius: 18px;
    padding: 0 15px;
    
    input {
      flex: 1;
      height: 100%;
      padding: 0 8px;
      font-size: 14px;
    }
    
    .clear-btn {
      padding: 5px;
    }
  }
}

/* 筛选栏样式 */
.filter-bar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 40px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .filter-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    flex: 1;
    font-size: 14px;
    color: #333;
    
    uni-icons {
      margin-left: 5px;
    }
  }
}

/* 订单列表样式 */
.order-list {
  padding: 10px;
  .no-result {
		text-align: center;
		padding: 30px 0;
		color: #999;
	}
  .order-item {
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 10px;
    padding: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .order-time {
        font-size: 13px;
        color: #666;
      }
      
      .order-status {
        font-size: 13px;
        padding: 2px 8px;
        border-radius: 4px;
      }
      
      .status-pending {
        color: #ff9900;
        background-color: #fff7e6;
      }
      
      .status-paid {
        color: #008000;
        background-color: #f0fff0;
      }
      
      .status-completed {
        color: #1890ff;
        background-color: #e6f7ff;
      }
      
      .status-canceled {
        color: #999;
        background-color: #f5f5f5;
      }
    }
    
    .order-content {
      display: flex;
      
      .order-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
      }
      
      .order-info {
        margin-left: 10px;
        flex: 1;
        
        .order-name {
          font-size: 15px;
          font-weight: 500;
          color: #333;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .order-desc {
          font-size: 13px;
          color: #666;
          margin-top: 5px;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
					min-height: 34rpx;
        }
        
        .order-bottom {
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          margin-top: 15px;
          
          .order-amount {
            font-size: 16px;
            font-weight: 500;
            color: #e64340;
          }
          
          .order-count {
            font-size: 13px;
            color: #999;
          }
        }
      }
    }
  }
}

/* 弹窗样式 */
.popup-content {
  background-color: #fff;
  border-radius: 12px 12px 0 0;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #eee;
    
    .popup-title {
      font-size: 16px;
      font-weight: 500;
    }
    
    .popup-close {
      padding: 5px;
    }
  }
  
  .popup-options {
    max-height: 300px;
    overflow-y: auto;
    // 优化iOS滚动体验
    -webkit-overflow-scrolling: touch;
    
    .option-item {
      padding: 15px;
      text-align: center;
      font-size: 15px;
      
      &.active {
        color: #1890ff;
        font-weight: 500;
      }
    }
  }
}

/* 加载状态样式 */
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px 0;
  color: #999;
  font-size: 14px;
  
  uni-icons {
    margin-right: 5px;
  }
}

/* 没有更多数据样式 */
.no-more-data {
  text-align: center;
  padding: 15px 0;
  color: #999;
  font-size: 14px;
}
</style>